﻿using Dapper.Extensions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Http;
using YouWei.Api.Common;
using YouWei.Api.Models;
using YouWei.Infrastructure.Entity;
using YouWei.Infrastructure.Models;
using YouWei.Infrastructure.Service;
using YouWei.Utility;

namespace YouWei.Api.Controllers
{
    /// <summary>
    /// 
    /// </summary>
    public class CommentController : BaseApiController
    {
        private CommentService _service = new CommentService();
        private CommentDetailService _serviceDetail = new CommentDetailService();
        private CommentImageService _serviceImgService = new CommentImageService();

        string imgUrl = ConfigHelper.GetAppSettingValue("FileUploadUrl");
        string imgListUrl = ConfigHelper.GetAppSettingValue("FileUploadYSUrl");


        /// <summary>
        /// 获取内容列表（分页）
        /// </summary>
        /// <param name="PageSize">每页条数</param>
        /// <param name="PageIndex">页码</param>
        /// <param name="OpenID">openId,仅做记录日志使用，不做查询</param>
        /// <param name="Section">文章所属板块（1：车趣杂谈 2：车友生活 3.丽人馆）</param>
        /// <param name="isHot">是否是热门推荐，1是0否</param>
        /// <returns></returns>
        [HttpGet]
        public ResultData<Page<CommentDto>> GetCommentList(int PageSize, int PageIndex, string OpenID, int Section, int isHot)
        {
            ResultData<Page<CommentDto>> result = ResultData<Page<CommentDto>>.Success();
            var commentData = _service.Pages(PageIndex, PageSize, OpenID, Section, isHot, "CommentID", "DESC");
            var ids = "";
            if (commentData.rows.Count > 0)
            {
                foreach (var comment in commentData.rows)
                {
                    ids += comment.CommentID;
                    ids += ",";
                    if (comment.HeadImgUrl != null && !comment.HeadImgUrl.StartsWith("http"))
                    {
                        comment.HeadImgUrl = imgListUrl + comment.HeadImgUrl;
                    }
                    if (comment.WxHeadImgUrl != null && !comment.WxHeadImgUrl.StartsWith("http"))
                    {
                        comment.WxHeadImgUrl = imgListUrl + comment.WxHeadImgUrl;
                    }
                }
                ids = ids.Substring(0, ids.Length - 1);
                List<CommentImage> imgList = _serviceImgService.PagesByCommentIDs(ids);
                foreach (var comment in commentData.rows)
                {
                    var list = new List<CommentImage>();
                    foreach (var img in imgList)
                    {
                        if (img.CommentID == comment.CommentID)
                        {
                            img.ImageUrl = img.ImageUrl.Replace(imgUrl, imgListUrl);
                            list.Add(img);
                        }
                    }
                    comment.CommentImgs = list;
                }
            }
            result.data = commentData;
            return result;
        }

        /// <summary>
        /// 获取置顶文章
        /// </summary>
        /// <param name="Section"></param>
        /// <returns></returns>
        public ResultData<CommentDto> GetTop(int Section)
        {
            var data = _service.GetTop(Section);
            if (string.IsNullOrEmpty(data.HeadImgUrl))
            {
                List<CommentImage> imgList = _serviceImgService.PagesByCommentID(data.CommentID);
                if (imgList.Count > 0)
                {
                    data.HeadImgUrl = imgList[0].ImageUrl;
                }
            }
            else
            {
                if (data.HeadImgUrl != null && !data.HeadImgUrl.StartsWith("http"))
                {
                    data.HeadImgUrl = imgUrl + data.HeadImgUrl;
                }
            }
            return ResultData<CommentDto>.Success(data);
        }

        /// <summary>
        /// 获取内容信息
        /// </summary>
        /// <param name="CommentID"></param>
        /// <returns></returns>
        [HttpGet]
        public ResultData<CommentDto> GetCommentInfo(int CommentID)
        {
            ResultData<CommentDto> result = ResultData<CommentDto>.Error("未查询到内容信息");
            var data = _service.GetCommentInfoById(CommentID);
            if (data != null && data.IsActive == 1)
            {
                if (data.HeadImgUrl != null && !data.HeadImgUrl.StartsWith("http"))
                {
                    data.HeadImgUrl = imgUrl + data.HeadImgUrl;
                }
                if (data.WxHeadImgUrl != null && !data.WxHeadImgUrl.StartsWith("http"))
                {
                    data.WxHeadImgUrl = imgUrl + data.WxHeadImgUrl;
                }
                result.status = 0;
                result.message = "查询成功";
                result.data = data;
            }
            return result;
        }

        /// <summary>
        /// 添加文章
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpPost]
        public ResultData<int> AddComment(CommentDto entity)
        {
            ResultData<int> result = ResultData<int>.Success("添加成功");
            if (string.IsNullOrEmpty(entity.CommentDesc))
            {
                if (!string.IsNullOrEmpty(entity.Detail))
                {
                    int lgh = entity.Detail.Length > 45 ? 45 : entity.Detail.Length;
                    entity.CommentDesc = entity.Detail.Substring(0, lgh);
                }
            }
            if (!string.IsNullOrEmpty(entity.HeadImgUrl))
            {
                entity.HeadImgUrl = entity.HeadImgUrl.Replace(imgUrl, "");
            }
            entity.CreateDate = DateTime.Now;
            entity.UpdateDate = DefultTime;
            entity.IsActive = 1;
            entity.IsShow = 1;
            result.data = EConvert.ToInt(_service.Insert(entity));
            var dentity = new CommentDetail()
            {
                CommentID = result.data,
                CreateDate = DateTime.Now,
                Detail = entity.Detail,
                UpdateDate = DefultTime
            };
            _serviceDetail.Insert(dentity);
            return result;
        }

        /// <summary>
        /// 更新内容
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public ResultData<string> UpdateComment(CommentDto entity)
        {
            var result = ResultData<string>.Success("修改成功");
            if (entity.CommentID <= 0)
            {
                result.status = -1;
                result.message = "缺少必要的参数ProductID";
                return result;
            }
            var model = _service.Single(entity.CommentID);
            if (model == null)
            {
                result.status = -1;
                result.message = "修改失败，信息不存在";
                return result;
            }

            if (!string.IsNullOrEmpty(entity.HeadImgUrl))
            {
                entity.HeadImgUrl = entity.HeadImgUrl.Replace(imgUrl, "");
            }
            entity.CreateDate = model.CreateDate;
            entity.IsActive = model.IsActive;
            entity.UpdateDate = DateTime.Now;
            var r = _service.Update(entity);
            if (!r)
            {
                var dentity = new CommentDetail()
                {
                    CommentID = entity.CommentID,
                    CreateDate = DateTime.Now,
                    Detail = entity.Detail,
                    UpdateDate = DateTime.Now
                };
                _serviceDetail.Update(dentity);
                result.status = -1;
                result.message = "修改失败";
            }
            return result;
        }

        /// <summary>
        /// 删除内容
        /// </summary>
        /// <param name="CommentID">主键ID</param>
        /// <returns></returns>
        [HttpPost]
        public ResultData<string> DeleteComment([FromUri] int CommentID)
        {
            ResultData<string> result = ResultData<string>.Success("删除成功");
            if (CommentID <= 0)
            {
                result.status = -1;
                result.message = "删除内容失败，缺少必要的参数";
            }
            var model = _service.Single(CommentID);
            if (model != null)
            {
                model.IsActive = 0;
                model.UpdateDate = DateTime.Now;
                var r = _service.Update(model);
                if (!r)
                {
                    result.status = -1;
                    result.message = "删除内容失败";
                }
            }
            return result;
        }


    }
}